<%@page import="entity.Admin" %>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<%
  String path = request.getContextPath();
  Admin admin = (Admin) session.getAttribute("admin");
  String deptName = "";
  if ("部门".equals(admin.getIsSuper())) {
    deptName = admin.getDeptName();
  }
%>

<div class="callout callout-left">
  <span class="callout-title text-muted">软件管理</span>
</div>

<div class="callout">
  <form class="form-inline" action="" method="post">
    <div class="form-group">
      <label for="softName_search">软件名称</label>
      <input type="text" class="form-control" id="softName_search" name="softName_search" placeholder="软件名称"
             autocomplete="off"/>
    </div>
    <div class="form-group">
      <label for="keySeg_search">密钥名称：</label>
      <input type="text" class="form-control" id="keySeg_search" name="keySeg_search" placeholder="密钥片段"
             autocomplete="off"/>
    </div>&nbsp;&nbsp;&nbsp;
    <button type="button" class="btn btn-primary" id="doSearch">
      <span class="glyphicon glyphicon-search">&nbsp;搜索</span>
    </button>&nbsp;&nbsp;&nbsp;
  </form>
</div>

<div class="callout callout-white">
  <div class="table-responsive">
    <table class="table table-hover">
      <thead>
      <tr>
        <th>编号</th>
        <th>软件名称</th>
        <th>所属商品</th>
        <th>密钥片段</th>
        <th>激活模式</th>
        <th>激活服务器</th>
        <th>密钥总量</th>
        <th>总分配数</th>
        <%--<th>部门许可数</th>--%>
        <th>用户分配数</th>
        <th>用户激活数</th>
        <th>状态</th>
        <th>创建时间</th>
        <th>动作</th>
      </tr>
      </thead>
      <tbody id="keys_content">
      </tbody>
    </table>
  </div>
</div>

<script>
require.config({
  baseUrl: '<%=path %>/js',
  paths: {
    jquery: 'jquery-1.9.1.min',
    common: 'common',
    bootstrapswitch: 'bootstrap-switch.min',
    bootstraptable: 'bootstrap-table.min'
  }
});
require(['jquery', 'common', 'bootstrapswitch', 'bootstraptable'], function ($, common) {
//console.log("商品管理模块载入");

var workspace = function () {

  var domKey;
  var dataOpt;
  var softwares;
  var deptSearch = "";

  var init = function () {
    domKey = common.commData.domKey;
    dataOpt = common.dataOpt;

    _initSoftsTable();
    _searchSoft();
  }

  // 分页功能
  var pageNav = function (htmlArr) {
    var opt = {
      htmlArr: htmlArr,
      content: $("#keys_content"),
    }
    common.pageNav(opt, function () {
      // 状态颜色
      $("[name='status_text']").each(function () {
        if ("正常" === $(this).html()) {
          $(this).addClass("text-success");
        } else {
          $(this).addClass("text-danger");
        }
      });

      deptLicenseModal();
      userLicenseModal();
      editSoft();
    });
  }

  // 初始化软件表格
  var _initSoftsTable = function () {
    softwares = common.ajaxLoadData(dataOpt.softwareOpt);
    dataOpt.softwareOpt.data = {}

    var template = " <tr><th>#row#</th>" +
      "<td>#softName#</td>" +
      "<td>#category#</td>" +
      "<td>#keySeg#</td>" +
      "<td>#actMode#</td>" +
      "<td>#kmsServer#</td>" +
      "<td>#numLic#</td>" +
      "<td>#assignedLic#</td>" +
      "<td>#userlic#</td>" +
      "<td>#usedlic#</td>" +
      "<td><span name='status_text'>#status#</span></td>" +
      "<td>#createDate#</td>" +
      "<td class='text-primary'>" +
      "<a href='#myModal' class='dept_lic' data-toggle='modal' data-softname='#softName#'><span class='glyphicon glyphicon-search'>部门许可</span></a>&nbsp" +
      "<a href='#myModal' class='user_lic' data-toggle='modal' data-softname='#softName#'><span class='glyphicon glyphicon-search'>用户激活</span></a>&nbsp;" +
      "<a href='#myModal' class='editSoft' data-toggle='modal' data-softname='#softName#'><span class='glyphicon glyphicon-edit'>编辑</span>" +
      "</td></tr>";

    var row = 0;
    var htmlArr = [];
    var html = "";
    var thisT = "";
    for (var i = 0, n = softwares.length; i < n; i++) {
      thisT = template;
      thisT = thisT.replace(/#row#/g, ++row).replace(/#softName#/g, softwares[i]["softName"]).replace(/#keySeg#/g, softwares[i]["keySeg"])
          .replace(/#actMode#/g, softwares[i]["actMode"]).replace(/#kmsServer#/g, softwares[i]["kmsServer"])
          .replace(/#userlic#/g, softwares[i]["userLicense"]) //.replace(/#deptlic#/g, softwares[i]["departLicense"])
          .replace(/#usedlic#/g, softwares[i]["usedLicense"]).replace(/#createDate#/g, softwares[i]["createDate"])
          .replace(/#category#/g, softwares[i]["category"]).replace(/#assignedLic#/g, softwares[i]["assignedLicense"])
          .replace(/#numLic#/g, softwares[i]["numLicense"]).replace(/#status#/g, softwares[i]["status"]);
      html += thisT;
      if ((row !== 0) && (row % common.commData.pageNum === 0)) {
        htmlArr.push(html);
        html = "";
      }
    }

    if ("" !== html) {
      htmlArr.push(html);// 插入不满pageNum的几条数据
    }

    pageNav(htmlArr);
  }

  // 部门分配详情
  var deptLicenseModal = function () {
    var modalBodyTemplate = "<div class='callout callout-white'>" +
      "<div class='table-responsive'>" +
      "<table class='table table-hover'>" +
      "<thead><tr>" +
      "<th>编号</th>" +
      "<th>部门名称</th>" +
      "<th>软件名称</th>" +
      "<th>许可数量</th>" +
      "<th>总分配数量</th>" +
      "<th>总激活数量</th>" +
      "<th>动作</th>" +
      "</tr></thead>" +
      "<tbody id='modal_license'>" +
      "</tr></tbody></table></div></div>";

    var template = "<tr><td>#id#</td>" +
      "<td>#deptName#</td>" +
      "<td>#softName#</td>" +
      "<td>#licenseNum#</td>" +
      "<td>#assigned#</td>" +
      "<td>#activated#</td>" +
      "<td><a href='javascript:;' class='user_dept_lic' data-deptname='#deptName#'><span class='glyphicon glyphicon-search'></span>用户激活情况</a></td></tr>";

    // 查看该部门下的用户激活情况
    var uesrDeptLicense = function (open) {
      $(".user_dept_lic").each(function () {
        var deptName = $(this).data("deptname");

        $(this).click(function () {
          $(open).next().click();
          deptSearch = deptName;
          $("#userlic_search").click();
        });
      });
    }

    $(".dept_lic").each(function () {
      var softName = $(this).data("softname");
      dataOpt.deptLicenseOpt.data = {
        "softName": softName,
        "deptName": encodeURI(encodeURI("<%=deptName %>"))
      }
      var deptLicenses = common.ajaxLoadData(dataOpt.deptLicenseOpt);

      $(this).click(function () {
        common.cleanModal();
        domKey.modal.find(".modal-dialog").addClass("modal-lg");
        domKey.modalLabel.html("部门分配详情");
        domKey.modalBody.html(modalBodyTemplate);
        domKey.modalAct.hide();
        var thisT = "";
        var html = "";
        for (var i = 0, n = deptLicenses.length; i < n; i++) {
          thisT = template;
          thisT = thisT.replace(/#id#/g, i + 1).replace(/#deptName#/g, deptLicenses[i]["deptName"]).replace(/#softName#/g, deptLicenses[i]["softName"])
              .replace(/#licenseNum#/g, deptLicenses[i]["licenseNum"]).replace(/#assigned#/g, deptLicenses[i]["assigned"]).replace(/#activated#/g, deptLicenses[i]["activated"]);
          html += thisT;
        }
        $("#modal_license").html(html);
        uesrDeptLicense(this);
      });
    });
  }

  // 用户激活详情
  var userLicenseModal = function (deptName) {
    var modalBodyTemplate = "<div class='callout'>" +
      "<form class='form-inline'>" +
      "<div class='form-group'>" +
      "<label for='userName_search'>账号：</label>" +
      "<input type='text' class='form-control' id='userName_search' name='userName_search' placeholder='用户账号' autocomplete='off' />" +
      "</div>&nbsp;&nbsp;&nbsp;" +
      "<button type='button' class='btn btn-primary' id='userlic_search'><span class='glyphicon glyphicon-search'>&nbsp;搜索</span></button>" +
      "</form></div>" +
      "<div class='callout callout-white'>" +
      "<div class='table-responsive'>" +
      "<table id='table'></table>" +
      "</div></div>";


    // 搜索用户账户
    var search = function (softName) {
      $("#userlic_search").click(function () {
        $("#table").bootstrapTable('destroy');
        var opt = {
          "softName": softName,
          "deptName": deptSearch,
          "userName": $("#userName_search").val()
        }
        initUserLicTable(opt);
      });
    }

    // 初始化表格
    var initUserLicTable = function (opt) {
      dataOpt.userLicenseOpt.data = {
        "softName": opt["softName"],
        "deptName": encodeURI(encodeURI(opt["deptName"])),// 选择的部门
        "userName": encodeURI(encodeURI(opt["userName"]))// 搜索
      }
      var userLicenses = common.ajaxLoadData(dataOpt.userLicenseOpt);
      dataOpt.userLicenseOpt.data = {}
      $('#table').bootstrapTable({
        data: userLicenses,
        sidePagination: 'client',
        smartDisplay: false,
        pagination: true,
        pageNumber: 1,
        pageSize: 1,
        pageList: [3, 5, 10],
        formatShowingRows: function (pageFrom, pageTo, totalRows) {
          return '';
        },
        formatRecordsPerPage: function (pageNumber) {
          return pageNumber + '条每页';
        },
        columns: [{
          field: 'id',
          title: '编号'
        }, {
          field: 'userName',
          title: '用户账号'
        }, {
          field: 'deptName',
          title: '部门名称'
        }, {
          field: 'softName',
          title: '软件名称'
        }, {
          field: 'assigned',
          title: '总分配量',
        }, {
          field: 'activated',
          title: '总激活量'
        }]
      });
    }

    $(".user_lic").each(function () {
      var softName = $(this).data("softname");
      var opt = {
        "deptName": "",// 每次点击清除选择的部门
        "softName": softName,// 固定软件
        "userName": ""
      }
      $(this).click(function () {
        common.cleanModal();
        domKey.modal.find(".modal-dialog").addClass("modal-lg");
        domKey.modalLabel.html("用户激活详情");
        domKey.modalBody.html(modalBodyTemplate);
        domKey.modalAct.hide();
        search(softName);
        initUserLicTable(opt);
      });
    });
  }

  // 编辑软件
  // 特定字段numLicense,status,kmsServer,keySeg
  var editSoft = function () {
    var modalBodyTemplate = "<form class='form-horizontal'>" +
      "<div class='form-group'>" +
      "<label for='softName' class='col-sm-4 control-label'>软件名称</label>" +
      "<div class='col-sm-8'>" +
      "<input class='form-control' id='softName' name='softName' type='text' readonly/>" +
      "</div></div>" +
      "<div class='form-group'>" +
      "<label for='numLic' class='col-sm-4 control-label'>密钥总量</label>" +
      "<div class='col-sm-8'>" +
      "<input class='form-control' id='numLic' name='numLic' type='number' min='0'/>" +
      "</div></div>" +
      "<div class='form-group'>" +
      "<label for='kmsServer' class='col-sm-4 control-label'>激活服务器</label>" +
      "<div class='col-sm-8'>" +
      "<input class='form-control' id='kmsServer' name='kmsServer' type='text' placeholder='激活服务器'/>" +
      "</div></div>" +
      "<div class='form-group'>" +
      "<label for='keySeg' class='col-sm-4 control-label'>密钥片段</label>" +
      "<div class='col-sm-8'>" +
      "<input  class='form-control' name='keySeg' id='keySeg' placeholder='密钥片段' />" +
      "</div></div>" +
      "<div class='form-group'>" +
      "<label for='status' class='col-sm-4 control-label'>状态</label>" +
      "<div class='col-sm-8'>" +
      "<select class='form-control' name='status' id='status'>" +
      "<option value='正常'>正常</option>" +
      "<option value='禁用'>禁用</option>" +
      "</select></div></div></form>";

    $(".editSoft").each(function () {
      $(this).click(function () {
        common.cleanModal();
        domKey.modal.find(".modal-dialog").addClass("modal-sm");
        domKey.modalLabel.html("编辑软件信息");
        domKey.modalBody.html(modalBodyTemplate);

        // 数据回填
        backFillData($(this).data("softname"));

        domKey.modalAct.html("保存")
        .on("click", function () {
          common.disable(domKey.modalAct);// 提交请求则禁掉按钮

          // 获取填写的数据
          var data = {
            "softName": $("#softName").val(),
            "numLicense": $("#numLic").val(),
            "kmsServer": $("#kmsServer").val(),
            "keySeg": $("#keySeg").val(),
            "status": $("#status").val()
          }

          if (data["numLicense"] < 0 || data["kmsServer"].length === 0 || data["keySeg"].length === 0) {
            alert("请正确填写所有信息");
            common.enable(domKey.modalAct);
          } else {
            $.ajax({
              url: "<%=path %>/servlet/soft/EditSoftServlet",
              type: "post",
              data: data,
              dataType: "json",
              async: false,
              success: function (json) {
                if ("1" === json["retCode"]) {

                } else {
                  alert(json["desc"]);
                }
              },
              error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("EditSoftServlet:" + XMLHttpRequest.status + ":" + XMLHttpRequest.readyState + ":" + textStatus);
              },
              complete: function () {
                domKey.modal.find(".close").click();
                _initSoftsTable();// 刷新表格
              }
            });
          }
        });
      });
    });


    var backFillData = function (sName) {
      for (var i = 0, n = softwares.length; i < n; i++) {
        if (softwares[i]["softName"] == sName) {
          $("#softName").val(softwares[i]["softName"]);
          $("#numLic").val(softwares[i]["numLicense"]);
          $("#kmsServer").val(softwares[i]["kmsServer"]);
          $("#keySeg").val(softwares[i]["keySeg"]);
          $("#status").val(softwares[i]["status"]);
          break;
        }
      }
    }
  }

  // 搜索密钥
  var _searchSoft = function () {
    $("#doSearch").click(function () {
      common.commData.curPage = 0;
      dataOpt.softwareOpt.data = {
        // softName
        "softName": encodeURI(encodeURI($("#softName_search").val())),
        "keySeg": encodeURI(encodeURI($("#keySeg_search").val()))
      }
      _initSoftsTable();
    });
  }

  return {
    init: init
  }
}();

$(function () { workspace.init(); });

});

requirejs.onError = function (err) {
  console.error(err);
  if (err.requireType === 'timeout') {
    console.error('modules: ' + err.requireModules);
  }
  throw err;
}
</script>
